package com.css.fxfzypg.app.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.config.property.FxfzConfig;
import com.css.fxfzypg.constants.R;
import com.css.fxfzypg.login.security.LoginSecretPool;
import com.css.fxfzypg.login.service.LoginService;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.slw.sso.config.SsoConfig;
import org.slw.sso.user.SsoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Slf4j
@RestController
@RequestMapping("/app/login")
public class AppLoginController {
    @Autowired
    FxfzConfig fxfzConfig;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    LoginService loginService;

    private static final String SESSION_RSAMAP_KEY = "PLATFORM_RSAMAP";
    private static final String PUBLIC_KEY = "PUBLIC_KEY";
    private static final String SESSION_ISCAPTCHA_KEY = "PLATFORM_ISCAPTCHA";
    private static final String SESSION_CAPTCHA_KEY = "PLATFORM_CAPTCHA";
    //读取配置文件
    Properties CONFIG_PROP = PropsHelper.loadProps("slw-config.properties");
    @Autowired
    SUserService sUserService;

    @GetMapping("/getSession")
    public String getSession(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = CONFIG_PROP.getProperty("getSessionIdUrl");
        Map<String, String> paramMap = new HashMap<>(10);
        paramMap.put("loginName",request.getParameter("loginName"));
        paramMap.put("password", Md5Util.getMD5(request.getParameter("password")));
        paramMap.put("loginType",request.getParameter("loginType"));
        String json = HttpClientUtil.doPost(url, paramMap);
        return json;
    }
    @GetMapping("/getTicket")
    public String getTicket(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = CONFIG_PROP.getProperty("getTicketUrl");
        Map<String, String> paramMap = new HashMap<>(10);
        paramMap.put("sessionId",request.getParameter("sessionId"));
        paramMap.put("secretKey","552d683bae934f7091732479a2370fa3");
        String json = HttpClientUtil.doPost(url, paramMap);
        if (PlatformObjectUtils.isNotEmpty(json)){
            Map<String,String> map = JSONObject.parseObject(json,Map.class);
            return json;
        }else {
            return null;
        }
    }
    @GetMapping("/getToken")
    public Map getToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //getSessionRHttpSession session = request.getSession();
        Map<String,Object> resMap= new HashMap<>();
        String token = null;
        String sessionUrl = CONFIG_PROP.getProperty("getSessionIdUrl");
        Map<String, String> paramMap = new HashMap<>(10);
        paramMap.put("loginName",request.getParameter("loginName"));
        paramMap.put("password",request.getParameter("password"));
        paramMap.put("loginType",request.getParameter("loginType"));
        String sessionJson = HttpClientUtil.doPost(sessionUrl, paramMap);
        System.out.println(sessionJson);
        Map<String,String> sessionMap = JSONObject.parseObject(sessionJson,Map.class);
        //Map<String,String> sessionMap = JSON.parseObject(JSON.toJSONString(sessionJson), new TypeReference<Map>() { } );
        String result =JSON.parseObject(
                JSON.toJSONString(sessionMap.get("result")),
                new TypeReference<String>() { } );
        if ("0".equals(result)){
            //getTicket
            String ticketUrl = CONFIG_PROP.getProperty("getTicketUrl");
            Map<String, String> ticketParamMap = new HashMap<>(10);
            ticketParamMap.put("sessionId",sessionMap.get("info"));
            ticketParamMap.put("secretKey",CONFIG_PROP.getProperty("appSecretkey"));
            String ticketJson = HttpClientUtil.doPost(ticketUrl, ticketParamMap);
            Map<String,String> ticketMap = JSONObject.parseObject(ticketJson,Map.class);
            String ticketresult =JSON.parseObject(
                    JSON.toJSONString(ticketMap.get("result")),
                    new TypeReference<String>() { } );
            if ("0".equals(ticketresult)){
                //getSsoUser
                String getTokenUrl = CONFIG_PROP.getProperty("getTokenUrl");
                Map<String, String> ssoUsserParamMap = new HashMap<>(10);
                ssoUsserParamMap.put("ticket",ticketMap.get("info"));
                String ssoJson = HttpClientUtil.doGet(getTokenUrl, ssoUsserParamMap);
                Map<String,Object> ssoMap = JSONObject.parseObject(ssoJson,Map.class);
                String ssoResult =JSON.parseObject(
                        JSON.toJSONString(ssoMap.get("result")),
                        new TypeReference<String>() { } );
                if ("0".equals(ssoResult)){
                    Object info = ssoMap.get("info");
                    SsoUser ssoUser = JSON.parseObject(
                           JSON.toJSONString(info),
                           new TypeReference<SsoUser>() { } );
                    token = PlatformJwtUtils.createToken(ssoUser.getUserId());
                    String userJson = sUserService.getSUser(ssoUser.getUserId());
                    SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
                    resMap.put("user",sUser);
                    resMap.put("token",token);
                    resMap.put("code","2000");
                    resMap.put("message",ssoMap.get("msg"));
                   /* HttpSession session = request.getSession();
                    String apptoken = (String) session.getAttribute("apptoken");
                    if (PlatformObjectUtils.isNotEmpty(apptoken)){
                        session.removeAttribute("apptoken");
                    }
                    session.setAttribute("apptoken",token);*/
                }
            }else {
                resMap.put("code","4002");
                resMap.put("message",ticketMap.get("msg"));
                return resMap;
            }
        }else {
            resMap.put("code","4002");
            resMap.put("message",sessionMap.get("msg"));
            return resMap;
        }
        return resMap;
    }
}

